Truncate Strings with Complete Words without chopping words half way In C#

Category > CSHARP || Published on : Wednesday, July 2, 2014 || Views: 6413 || Truncate Strings in C# truncate strings C Sharp string separations string truncate without chopping in C# string truncate


In some situation, we have to chop some words from a given string but using substring we can't achieve this and loose some characters. Below is the method which can chop the given string


Here I'm demonstrating two methods to help in truncate string with complete words without chopping words


Step 1: Create a console application.

create-console-application

Step 2: Create class “ExtensionMethods.” As below

 public static class ExtensionMethods
        {
    public static string TruncateWithoutChopping(this string strText, int intLength)
        {
    if (String.IsNullOrEmpty(strText))
    throw new ArgumentNullException();
        var words = strText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        var sbText = new StringBuilder();
    foreach (var word in words.Where(word => (sbText.ToString().Length + word.Length) <= intLength))
        {
        sbText.Append(word + " ");
        }
    return sbText.ToString().TrimEnd(' ') + "...";
        }
        }
Step 3: Call the “TruncateWithoutChopping” method in main program

     class Program
        {
            static void Main(string[] args)
        {
            string strTest = "this is the word to truncate";
            string TruncateString = strTest.TruncateWithoutChopping(10);
        Console.ReadLine();
        }
        }

Step 4: See the output as we need.

output
You can also download the source codes below

Download Source Codes